package com.mtk.launcher.activity;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.cdl.library.dialog.OridinryDialog;
import com.cdl.library.listener.MoreButtonListener;
import com.cdl.library.listener.MoreButtonToggleListener;
import com.cdl.library.listener.OridinryDialogClick;
import com.lark.wifi.util.MyLog;
import com.mtk.launcher.BuildConfig;
import com.mtk.launcher.R;
import com.mtk.launcher.databinding.ActivitySettingScreenShowBinding;
import com.mtk.launcher.power.activity.PowerManagerActivity;
import com.mtk.launcher.power.bean.TimeDealEntity;
import com.mtk.launcher.util.SimpleDateUtil;
import com.mtk.launcher.util.shared.SharedPerManager;

public class ScreenShowActivity extends BaseActivity {

    ActivitySettingScreenShowBinding binding;
    long currentTimeStart = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySettingScreenShowBinding.inflate(getLayoutInflater());
        currentTimeStart = System.currentTimeMillis();
        setContentView(binding.getRoot());
        initView();
        initListener();
    }

    private void initListener() {
        binding.settingSleep.setOnMoretListener(new MoreButtonListener() {
            @Override
            public void clickView(View view) {
                startActivity(new Intent(ScreenShowActivity.this, SleepActivity.class));
            }
        });
        binding.radio0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeScreenRotation(Surface.ROTATION_0);
            }
        });
        binding.radio90.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeScreenRotation(Surface.ROTATION_90);
            }
        });
        binding.radio180.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeScreenRotation(Surface.ROTATION_180);
            }
        });
        binding.radio270.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeScreenRotation(Surface.ROTATION_270);
            }
        });

        binding.included.llBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                int screenLight = progress * 255 / 100;
                setScreenBrightness(screenLight);
                binding.tvScreenLight.setText(progress + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        binding.toggleSwitchPower.setOnMoretListener(new MoreButtonToggleListener() {
            @Override
            public void switchToggleView(View view, boolean isClick) {
                SharedPerManager.setPowerOnOffEnable(isClick ? 1 : 0);
                updateMainView();
            }
        });

        binding.settingPower.setOnMoretListener(new MoreButtonListener() {
            @Override
            public void clickView(View view) {
                startActivity(new Intent(ScreenShowActivity.this, PowerManagerActivity.class));
            }
        });

    }

    private void initView() {
        binding.included.title.setText(R.string.setting_screen_show);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateMainView();
    }

    private void updateMainView() {
        TimeDealEntity timeDealEntity = SharedPerManager.getPowerOnOffTime();
        if (timeDealEntity == null) {
            binding.settingSleep.setVisibility(View.VISIBLE);
        } else {
            binding.settingSleep.setVisibility(View.GONE);
        }
        int screenLightNum = getScreenBrightnessInt();
        int progress = screenLightNum * 100 / 255;
        binding.tvScreenLight.setText(progress + "%");
        binding.seekBar.setProgress(progress);
        int screenRoate = getScreenRotation();
        MyLog.cdl("screenRoate==" + screenRoate);
        binding.radio0.setTextColor(getColor(R.color.grey));
        binding.radio90.setTextColor(getColor(R.color.grey));
        binding.radio180.setTextColor(getColor(R.color.grey));
        binding.radio270.setTextColor(getColor(R.color.grey));
        switch (screenRoate) {
            case Surface.ROTATION_0:
                binding.tvRoateNum.setText("0");
                binding.radio0.setSelected(true);
                binding.radio0.setTextColor(getColor(R.color.white));
                break;
            case Surface.ROTATION_90:
                binding.tvRoateNum.setText("90");
                binding.radio90.setSelected(true);
                binding.radio90.setTextColor(getColor(R.color.white));
                break;
            case Surface.ROTATION_180:
                binding.tvRoateNum.setText("180");
                binding.radio180.setSelected(true);
                binding.radio180.setTextColor(getColor(R.color.white));
                break;
            case Surface.ROTATION_270:
                binding.tvRoateNum.setText("270");
                binding.radio270.setSelected(true);
                binding.radio270.setTextColor(getColor(R.color.white));
                break;
        }

        binding.toggleSwitchPower.setSwitchStatues(SharedPerManager.getPowerOnOffEnable());
        binding.toggleSwitchPower.setTxtContent(SharedPerManager.getPowerOnOffEnable() ? "开" : "关");
        binding.settingPower.setVisibility(SharedPerManager.getPowerOnOffEnable() ? View.VISIBLE : View.GONE);
        String offTime = SimpleDateUtil.getShowOnOffTime(this, timeDealEntity, 0);
        String onTime = SimpleDateUtil.getShowOnOffTime(this, timeDealEntity, 1);
        binding.settingPower.setTxtContent(offTime + " - " + onTime);
    }

    /***
     * 获取屏幕亮度
     * @return
     */
    public int getScreenBrightnessInt() {
        try {
            ContentResolver resolver = getContentResolver();
            return Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            return 128;
        }
    }

    // 设置系统屏幕亮度（0-255）
    public void setScreenBrightness(int brightnessValue) {
        try {
            // 关闭自动亮度调节
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            // 设置亮度值
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessValue);
            // 更新当前窗口的亮度（可选）
            WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
            layoutParams.screenBrightness = brightnessValue / 255.0f;
            getWindow().setAttributes(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 切换屏幕旋转角度
     */
    private void changeScreenRotation(int rotationSet) {
        if (BuildConfig.DEBUG) {
            return;
        }
        int screenRotation = getScreenRotation();
        if (screenRotation == rotationSet) {
            MyLog.cdl("changeScreenRotation, 已经是" + rotationSet + "度了");
            return;
        }
        // 弹出确认对话框

        OridinryDialog oridinryDialog = new OridinryDialog(this);
        oridinryDialog.setOnDialogClickListener(new OridinryDialogClick() {
            @Override
            public void sure() {
                // 用户点击确定，设置屏幕旋转角度
                try {
                    Settings.System.putInt(getContentResolver(),
                            Settings.System.USER_ROTATION, rotationSet);
                    Toast.makeText(ScreenShowActivity.this, "屏幕旋转已设置为 " + rotationSet * 90 + " 度", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Toast.makeText(ScreenShowActivity.this, "设置失败，请检查权限", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void noSure() {

            }
        });
        oridinryDialog.show(getString(R.string.str_tip), "是否将屏幕旋转设置为 " + rotationSet * 90 + " 度？");
    }

    // 获取当前屏幕的旋转角度（0、90、180、270 度）
    public int getScreenRotation() {
        if (BuildConfig.DEBUG) {
            return Surface.ROTATION_0;
        }
        return Settings.System.getInt(
                getContentResolver(),
                Settings.System.USER_ROTATION,
                Surface.ROTATION_0);
//        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
//        Display display = windowManager.getDefaultDisplay();
//        return display.getRotation();
    }

}
